package com.yhm.myfootbollshow.demos.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhm.myfootbollshow.demos.base.ResVo;
import com.yhm.myfootbollshow.demos.entity.dto.LoginUser;
import com.yhm.myfootbollshow.demos.entity.dto.UserDto;
import com.yhm.myfootbollshow.demos.entity.dto.banUser;
import com.yhm.myfootbollshow.demos.entity.po.Merchant;
import com.yhm.myfootbollshow.demos.entity.po.User;
import com.yhm.myfootbollshow.demos.entity.po.UserAddress;
import com.yhm.myfootbollshow.demos.entity.vo.UserVo;
import com.yhm.myfootbollshow.demos.mapper.MerchantMapper;
import com.yhm.myfootbollshow.demos.mapper.UserAddressMapper;
import com.yhm.myfootbollshow.demos.mapper.UserMapper;
import com.yhm.myfootbollshow.demos.service.UserService;
import com.yhm.myfootbollshow.demos.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @description:
 * @author: yhm
 * @time: 2025/3/31 13:20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private MerchantMapper mapper;
    @Autowired
    private UserAddressMapper addressMapper;
    @Override
    public ResVo Login(LoginUser loginUser) {
        // 判断账号密码是否为空
        if (loginUser.getUsername() != null && loginUser.getPassword() != null) {
            if (loginUser.getRole().equals("merchant")){
                Merchant merchant = mapper.selectOne(
                        new LambdaQueryWrapper<Merchant>()
                                .eq(Merchant::getUsername, loginUser.getUsername())
                );
                if (merchant != null){
                    if (merchant.getStatus() == 0){
                        // 账号被禁用
                        return ResVo.error("账号被禁用");
                    }
                    if (new BCryptPasswordEncoder().matches(loginUser.getPassword(), merchant.getPassword())){
                        // 登录成功
                        HashMap<String, String> map = new HashMap<>();
                        map.put("username", merchant.getUsername());
                        map.put("merchantId", merchant.getMerchantId().toString());
                        map.put("role", "merchant");
                        String token = JWTUtils.getToken(map);
                        map.put("token",token);
                        UserVo userVo = new UserVo();
                        userVo.setUsername(merchant.getUsername());
                        userVo.setUserId(merchant.getMerchantId().toString());
                        userVo.setRole("merchant");
                        userVo.setToken(token);
                        return ResVo.ok(userVo);
                    }
                    return ResVo.error("账号或密码错误");
                }else {
                    return ResVo.error("账号或密码错误");
                }
            }



            // 查询数据库
            User user = baseMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, loginUser.getUsername())
                    .eq(User::getRole, loginUser.getRole()));
            // 判断账号是否存在
            if (user != null) {
                if (user.getStatus() == 0) {
                    // 账号被禁用
                    return ResVo.error("账号被禁用");
                }
                if (!user.getRole().equals(loginUser.getRole()) ){
                    return ResVo.error("该用户没有对应角色");
                }
                // 判断密码是否正确
                if (new BCryptPasswordEncoder().matches(loginUser.getPassword(), user.getPassword())) {
                    // 登录成功
                    HashMap<String, String> map = new HashMap<>();
                    map.put("username", user.getUsername());
                    map.put("userId", user.getUserId().toString());
                    map.put("role", user.getRole());
                    String token = JWTUtils.getToken(map);
                    map.put("token",token);
                    UserVo userVo = new UserVo();
                    userVo.setUsername(user.getUsername());
                    userVo.setUserId(user.getUserId().toString());
                    userVo.setRole(user.getRole());
                    userVo.setToken(token);
                    return ResVo.ok(userVo);
                } else {
                    // 密码错误
                    return ResVo.error("密码错误");
                }
            } else {
                // 账号不存在
                return ResVo.error("账号不存在");
            }
        } else {
            // 账号密码为空
            return ResVo.error("账号或密码为空");
        }
    }

    @Override
    public Boolean register(User user) {
        if (user.getUsername() != null && user.getPassword() != null) {
            // 判断账号是否存在
            User user1 = baseMapper.findByUsername(user.getUsername());
            if (user1 != null) {
                // 账号已存在
                return false;
            } else {
                // 账号不存在
                // 加密密码
                user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
                user.initUser();
                user.setRole("user");
                // 插入数据库
                baseMapper.register(user);
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean banUser(banUser user) {
        System.out.println("进入禁用用户");
        System.out.println(user.toString());
        if (user.getUserId() != null && user.getUsername() != null && user.getNewStatus() != null) {
            LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(User::getUserId,user.getUserId())
                    .eq(User::getUsername,user.getUsername())
                    .set(User::getStatus,user.getNewStatus());
            return baseMapper.update(wrapper)>0;
        }
        return false;
    }

    @Override
    public IPage<User> list(UserDto user) {
        // 判断user是否为空
        if (user == null) {
            return null;
        }
        Page<User> userPage = new Page<>(1,10);
        userPage.setCurrent(user.getPageNum());
        userPage.setSize(user.getPageSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User.class,info -> !info.getProperty().equals("password"));
        wrapper.like(user.getUsername() != null&& !user.getUsername().isEmpty(),User::getUsername,user.getUsername())
                .eq(user.getStatus() != null&& !user.getStatus().isEmpty(),User::getStatus,user.getStatus())
                .eq(User::getRole,"user");
        return userPage.setRecords(baseMapper.selectList(userPage,wrapper));
    }

    @Override
    public Boolean updateUser(Long userId, String username, String password) {
        if (userId != null && username != null && password != null) {
            if (!username.isEmpty()&&!password.isEmpty()){
                LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(User::getUserId,userId)
                        .eq(User::getUsername,username)
                        .set(User::getPassword,new BCryptPasswordEncoder().encode(password));
                return baseMapper.update(wrapper)>0;
            }
        }
        return false;
    }

    @Override
    public List<UserAddress> listAdd(Long userId) {
        if (userId != null) {
            LambdaQueryWrapper<UserAddress> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserAddress::getUserId,userId);
            return addressMapper.selectList(wrapper);
        }
        return null;
    }

    @Override
    public Boolean addAddress(UserAddress userAddress) {
        if (userAddress != null && isUserAddressValid(userAddress)) {
            try {
                LambdaUpdateWrapper<UserAddress> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(UserAddress::getUserId, userAddress.getUserId())
                        .set(UserAddress::getIsDefault, 0);
                addressMapper.update(null, wrapper);
                userAddress.setIsDefault(1);
                return addressMapper.insert(userAddress) > 0;
            } catch (Exception e) {
                // 处理异常，例如记录日志或抛出自定义异常
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    private boolean isUserAddressValid(UserAddress userAddress) {
        return userAddress.getUserId() != null &&
                userAddress.getReceiverName() != null && !userAddress.getReceiverName().isEmpty() &&
                userAddress.getReceiverPhone() != null && !userAddress.getReceiverPhone().isEmpty() &&
                userAddress.getProvince() != null && !userAddress.getProvince().isEmpty() &&
                userAddress.getCity() != null && !userAddress.getCity().isEmpty() &&
                userAddress.getDistrict() != null && !userAddress.getDistrict().isEmpty() &&
                userAddress.getDetailAddress() != null && !userAddress.getDetailAddress().isEmpty();
    }
}
